package com.stray.crawl.expr.act;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.stray.crawl.ResultContext;
import com.stray.crawl.TaskContext;
import com.stray.crawl.expr.EventData;
import com.stray.crawl.expr.Express;

public class FollowUrlAction extends Express {

	private static final String FOLLOW_URL = "FOLLOW_URL";
	private final Log log = LogFactory.getLog(this.getClass());

	@SuppressWarnings("unchecked")
	@Override
	protected Object doParse(EventData event) {
		Object obj = event.getObject();
		TaskContext taskContext = event.getTaskContext();
		
		try {
			URI uri = taskContext.getUrl().toURI();
			
			ResultContext resultContext = event.getResultContext();
			List<String> followUrls = (List<String>) resultContext.getAttribute(FOLLOW_URL);
			if (followUrls == null) {
				followUrls = new ArrayList<String>();
				resultContext.putAttribute(FOLLOW_URL, followUrls);	
			}

			String href = (String) obj;
			String url = uri.resolve(href).toString();
			followUrls.add(url);
		} catch (URISyntaxException ex) {
			log.info("Fail to get follow url from obj : " + obj, ex);
		}

		return obj;
	}

}
